<?php
	
require_once '../mysqlConnect.php'; //mysqli database connect
	
function Login($email, $password) //checks user email/password combination
{
	$conn = GetConnection();
	if ($conn->connect_errno) {
		echo $conn->connect_error;
		echo $conn->error;
		die();
	}
	
	$sql = sprintf("SELECT ID, Email, Password FROM Administrator WHERE Email='%s'",
	mysqli_real_escape_string($conn, $email),
	mysqli_real_escape_string($conn, $password));
		
	$result = $conn->query($sql);
	
	if($conn->error)
		return array('loginEmail', 'Email', 'Invalid Email');
	else	
		$rs = $result->fetch_assoc();
	
	if(!$rs)
		return array('loginEmail', 'Email', 'No Such User');
		
	$conn->close();
	
	$hash = hash('sha256', $password);
	if($rs['Password'] != $hash) 
		return array('loginPass', 'Password', 'Incorrect Password');
	
	validateUser($rs['ID']);
	return null;
}

function validateUser($id)
{
	$_SESSION['UserId'] = $id;
}

function getUserID()
{
	return $_SESSION['UserId'];
}
function logout()
{
    $_SESSION = array();
    session_destroy();
}
function getPatientNum()
{
	return $_SESSION['PatID'];
}
function getPatientInfobyId($id)
{
	$conn = GetConnection();
	$result = $conn->query("SELECT * FROM Patient WHERE ID = '$id'");
	$rs = $result->fetch_assoc();
	return $rs;
	$conn->close();
}
function clearSessionSaveAdmin()
{
	$dontDelete = array('UserId');
	foreach($_SESSION as $key => $value) {
	   if (!in_array($key,$dontDelete)) 
		  unset($_SESSION[$key]);  
	}
}
function checkEmail($email, $userID)
{
	$conn = GetConnection();
	$result = $conn->query("SELECT * FROM Administrator A WHERE A.Email = '$email'");
	if($conn->error != null) return array('changePassEmail', 'Email', 'Invalid Email');
	$rs = $result->fetch_assoc();
	$conn->close();
	if ($userID != $rs['ID']) return array('changePassEmail', 'Email', 'Wrong Email for Current User');
	return null;
}
function checkPassword($pass)
{
	$conn = GetConnection();
	$id = getUserID();
	$result = $conn->query("SELECT * FROM Administrator A WHERE A.ID = '$id'");
	$rs = $result->fetch_assoc();
	$conn->close();
	$hash = hash('sha256', $pass);
	if($rs['Password'] != $hash) return array('changePassPass', 'CurrPassword', 'Incorrect Password');	
	return null;
}
function checktwoPasswords($pass1, $pass2)
{
	if ($pass1 == null)
		return array('changePassNew', 'Password1', 'You Need to Provide a New Password');
	if ($pass2 == null)
		return array('changePassReNew', 'Password2', 'You Need to Provide a New Password');
	if ($pass1 != $pass2)
		return 'Passwords Do Not Match';
	return null;
}
function changePassword($pass, $userID)
{
	$conn = GetConnection();
	$hash = hash('sha256', $pass);
	$query = "UPDATE Administrator SET Password='$hash' WHERE ID = '$userID'";
	$conn->query($query);
	$conn->close();
}